<template>
  <div id="result-map" style="width:100%;height:200px;"></div>
</template>
<script>
import '@/assets/map/ol/ol.css';
import { getProjection } from "@/map/projMap.js";
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import {Cluster, Vector as VectorSource, XYZ} from 'ol/source'
import {Control, defaults as defaultControls} from 'ol/control';
import WKT from 'ol/format/WKT';
import Overlay from 'ol/Overlay';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import LineString from 'ol/geom/LineString';
import {Fill, Stroke, Style, Icon, Circle,Text} from 'ol/style';
import {boundingExtent} from 'ol/extent';
import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';

export default {
  name: "resultMap",
  components: {

  },
  props:{
    geomText: {//空间数据
      type:String,
      required:true,
      default:""
    }
  },
  emits:[],
  data() {
    return {
      str: "result",
      map: null,
      projection4490:null,
      center: [105, 34],
      zoom: 4,
      layer1:null,//天地图街道图
      layer2:null,
      //空间数据
      geomVectorLayer:null,//矢量数据图层
    }
  },
  watch: {
    geomText: {//空间数据
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          console.log(newVal);
          //显示矢量数据
          this.showGeomText();
        }
      },
      immediate:true
    },
  },
  created() {

  },
  mounted() {
    //console.log("mounted");
    let that = this;
    //地图异步加载
    this.$nextTick(function(){
      //console.log('地图异步加载');
      //地图异步加载
      setTimeout(() => {
        //初始化地图信息
        that.initMap();
        //显示矢量数据
        that.showGeomText();
      }, 200);
    });
  },
  beforeCreate() {//生命周期创建之前
    //console.log("beforeCreate");
  },
  beforeMount() {//生命周期挂载之前
    //console.log("beforeMount");
  },
  beforeUpdate() {//生命周期更新之前
    //console.log("beforeUpdate");
  },
  updated() {//生命周期更新之后
    //console.log("updated");
  },
  beforeDestroy() {//生命周期销毁之前
    //console.log("beforeDestroy");
  },
  destroyed() {//生命周期销毁完成
    this.map = null;
    //console.log("销毁地图");
  },
  activated() {//如果页面有keep-alive缓存功能激活，这个函数会触发
    //console.log("activated-"+this.str);
    /*//自动获取地图div高度
    this.autodivheight();
    //浏览器窗口发生变化时同时变化DIV高度
    window.onresize=this.autodivheight;*/
  },
  deactivated() {//如果页面有keep-alive缓存功能停用，这个函数会触发
    //console.log("deactivated-"+this.str);
    //取消浏览器窗口发生变化时同时变化DIV高度事件
    window.onresize = null;
  },
  methods: {
    initMap() {
      let that = this;
      let mapStr = this.str;
      let targetMap = document.getElementById(mapStr+"-map");
      if(targetMap.innerHTML!=""){
        //console.log("清空targetMap");
      }
      targetMap.innerHTML = "";//清空
      /*//自动获取地图div高度
      this.autodivheight();
      //浏览器窗口发生变化时同时变化DIV高度
      window.onresize=this.autodivheight;*/
      if(this.map){//避免重复加载地图
        console.log("避免重复加载地图");
        return;
      }
      console.log("初始化地图");
      //获取投影4490坐标系
      this.projection4490 = getProjection();
      //初始化地图信息
      this.map = new Map({
        target: targetMap.id,
        /*controls: defaultControls({attributionOptions: {collapsed: false}})
            .extend([new Logo()]),*/
        view: new View({
          center: this.center,
          maxZoom: 18,
          zoom: this.zoom,
          projection: 'EPSG:4490'
        })
      });
      //添加天地图图层
      this.layer1 = new TileLayer({
        title: '天地图街道地图底图',
        source: new XYZ({
          url: 'http://t0.tianditu.gov.cn/vec_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=0bfd57475542d76f12578a701d2a70ab',
          projection: "EPSG:4490"
        })
      });
      this.map.addLayer(this.layer1);
      this.layer2 = new TileLayer({
        title: '天地图街道地图',
        source: new XYZ({
          url: 'http://t0.tianditu.gov.cn/cva_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=0bfd57475542d76f12578a701d2a70ab',
          projection: "EPSG:4490"
        })
      });
      this.map.addLayer(this.layer2);
      this.layer1.setZIndex(0);
      this.layer2.setZIndex(0);
      //矢量数据图层
      this.geomVectorLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.geomVectorLayer);
      this.geomVectorLayer.setZIndex(4);
    },
    autodivheight() {//自动获取div高度
      //获取浏览器窗口高度
      let winHeight = 0;
      if (window.innerHeight) {
        winHeight = window.innerHeight;
      } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
      }
      //通过深入Document内部对body进行检测，获取浏览器窗口高度
      if (document.documentElement && document.documentElement.clientHeight) {
        winHeight = document.documentElement.clientHeight;
      }
      //全屏时窗口高度:864px,地图div高度:754px
      let tempHeight = 864;
      let mapTempHeight = 754;
      let mapHeight = winHeight - tempHeight + mapTempHeight;
      //最小高度
      if(mapHeight < 525){
        mapHeight = 525;
      }
      //设置地图高度
      if(document.getElementById(this.str+"-map")){
        document.getElementById(this.str+"-map").style.height= mapHeight +"px";
      }
      //console.log("窗口高度："+winHeight+"地图高度："+mapHeight);
      //resize事件--刷新地图,确保地图不变形
      if(this.map){
        this.map.updateSize();
        //console.log("resize事件--刷新地图,确保地图不变形");
      }
    },
    getPointStyle(){//点图标样式
      let style = new Style({
        image: new Icon({
          src: dingweiImg,
          anchor: [0.5, 1]
        }),
      });

      return style;
    },
    getLineStringStyle(color){//线样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(0,0,0,0)"
        }),
        stroke:new Stroke({//线
          width:2,//宽
          color:color
        })
      });

      return style;
    },
    getPolyonStyle(color){//多边形样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(0,0,0,0)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:color
        })
      });

      return style;
    },
    numberAround(number,len){
      // 四舍五入保留len位小数
      return number.toFixed(len);
    },
    //处理经纬度
    getLonLat(longitude,latitude){
      let lonlat = null;
      if(longitude!=null && latitude!=null && longitude!="" && latitude!=""){
        let lon = Number(longitude);
        let lat = Number(latitude);
        if(lon>0 && lon<180 && lat>0 && lat<90){
          lonlat = [lon,lat];
        }
      }

      return lonlat;
    },
    showGeomText(){//显示矢量数据
      console.log("显示矢量数据");
      if(this.geomVectorLayer!=null){
        this.geomVectorLayer.getSource().clear();//清空
        if(this.geomText!=null && this.geomText!=""){
          let geomText = this.geomText.toUpperCase();//转换大写字母
          if(geomText.indexOf("POINT")!=-1 || geomText.indexOf("MULTIPOINT")!=-1 ||
              geomText.indexOf("LINESTRING")!=-1 || geomText.indexOf("MULTILINESTRING")!=-1 ||
              geomText.indexOf("POLYGON")!=-1 || geomText.indexOf("MULTIPOLYGON")!=-1) {//矢量数据
            //空间数据
            let featureTmp = new WKT().readFeature(geomText);
            if(geomText.indexOf("POINT")!=-1 || geomText.indexOf("MULTIPOINT")!=-1){//点
              //样式
              let style = this.getPointStyle();
              featureTmp.setStyle(style);
            }else if(geomText.indexOf("LINESTRING")!=-1 || geomText.indexOf("MULTILINESTRING")!=-1){//线
              //样式
              let style = this.getLineStringStyle("blue");
              featureTmp.setStyle(style);
            }else if(geomText.indexOf("POLYGON")!=-1 || geomText.indexOf("MULTIPOLYGON")!=-1){//面
              //样式
              let style = this.getPolyonStyle("blue");
              featureTmp.setStyle(style);
            }
            //添加矢量数据
            this.geomVectorLayer.getSource().addFeature(featureTmp);
            //全部经纬度
            let allCoordinates = [];
            //获取范围
            let extent = featureTmp.getGeometry().getExtent();
            if(extent.length==4){
              //全部经纬度--左下角
              allCoordinates.push([extent[0],extent[1]]);
              //全部经纬度--右上角
              allCoordinates.push([extent[2],extent[3]]);
            }
            this.showBoundingExtent(allCoordinates);//缩放到区域位置
          }
        }
      }
    },
    showBoundingExtent(coordinates){//缩放到区域位置
      //console.log("缩放到区域位置");
      if (coordinates!=null && coordinates.length > 1) {
        const extent = boundingExtent(coordinates);
        //this.map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
        this.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
        //获取默认位置
        this.center = this.map.getView().getCenter();
        this.zoom = this.map.getView().getZoom();
      }
    }
  }
}

</script>

<style scoped>

</style>